package http;

import model.ApiConfigDataModel;
import model.ApiDataModel;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by yangxianming on 2015-06-10.
 */
public class HttpGroup {
    ArrayList<ApiDataModel> admlist = null;
    ApiConfigDataModel acdm = null;

    public HttpGroup(ArrayList<ApiDataModel> admlist, ApiConfigDataModel acdm){
        this.admlist = admlist;
        this.acdm = acdm;
    }

    public void http(){
        PrintWriter printWriter = null;
        try {
            printWriter =
                    new PrintWriter(new FileWriter(new File(System.getProperty("user.dir") + "//logs//" + "logs.log"), true));
        }catch (IOException e){
            e.printStackTrace();
        }

        for (ApiDataModel adm:admlist){
            System.out.printf("%nApiId.(%s) START test %s ↓↓↓↓↓↓%n",adm.apiId , adm.url);
            Http http = new Http(adm, acdm);
            try {
                http.httpDo();
            }catch (Exception e){
//                e.printStackTrace();
                adm.testResultAnalysisModel.result = false;     //异常后直接设置测试结果为false
                adm.testResultAnalysisModel.describe = e.getMessage();      //将异常原因保存起来
                System.out.printf("%n! ! ! ! get message -- %s -- %n", e.getMessage());
                printWriter.println(new Date());
                printWriter.println(getErrorInfoFromException(e));
                if (adm.isExceptionStop){
                    System.out.printf("%n! ! ! ! %s test exception, BREAK test ! ! ! !%n", adm.url);
                    break;
                }else {
                    System.out.printf("%n---- %s test exception, CONTINUE test ----%n", adm.url);
                    continue;
                }
            }
            System.out.printf("%nEND test %s -------%n", adm.url);
        }
        printWriter.close();
    }

    private String getErrorInfoFromException(Exception e) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            return "\r\n" + sw.toString() + "\r\n";
        } catch (Exception e2) {
            return "bad getErrorInfoFromException";
        }
    }

}
